package com.tnstart.net
{
	
	import com.tnstart.DataSingleton;
	import com.tnstart.vo.Config;
	import com.tnstart.vo.Item;
	import com.tnstart.beans.ControlCommandBean;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	import spark.components.View;
	
	
	public class LocalHomeControlSocketDataImpl extends EventDispatcher
	{
		public static var HEAD_LEN:uint = 6;
		//HEAD
		public static var SYN_HEAD:uint = 0x55 & 0xff;
		public static var DEST_NET_ID:uint = 0x01 & 0xff;
		public static var SRC_NET_ID:uint = 0x00 & 0xff;
		public static var SRC_DEVICE_ID:uint = 0x00 & 0xff;
		
		//CONTROL
		public static var FRAME_TYPE_CONTROL:uint = 0x01 & 0xff;
		public static var CONTROL_TYPE_ONEWAY_SWITCH = 0x01 & 0xff;
		public static var CONTROL_TYPE_ONEWAY_DIMMER = 0x02 & 0xff;
		
		public static var TAIL:uint = 0xaa & 0xff;
		
		private var _dataToPush:DataSingleton;
		
		private static var instance:LocalHomeControlSocketDataImpl;
		
		private var _host:String; 
		private var _port:int;
		private var socket:Socket;
		private var _tnStartCurrectView:View;
		
		public function LocalHomeControlSocketDataImpl()
		{
			socket = new Socket();
			socket.timeout = 3000;
			socket.addEventListener(Event.CLOSE,onClose);
			socket.addEventListener(Event.CONNECT, onConnected);
			socket.addEventListener(IOErrorEvent.IO_ERROR,onSocketOnError);
			socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSocketOnSecurityError); 
			socket.addEventListener(ProgressEvent.SOCKET_DATA,onSocketOnDataGet);
		}
		
		private function reSetHostAndPort():void
		{	
			if(_dataToPush != null)
			{
				var config:Config = _dataToPush.dbManager.configDAO.get(1);
				_host = config.host;
				_port = config.port;
			}
		}
		
		private function conn():void
		{	
			reSetHostAndPort();
			socket.connect(_host, _port);
		}
			
		protected function onSocketOnDataGet(event:ProgressEvent):void
		{
			while(socket.bytesAvailable >= 5)
			{
				var byteArray:ByteArray = new ByteArray();
				socket.readBytes(byteArray, 0, 5);
				//processBackUnitData(byteArray);
			}
			eventToTnStartCurrenctView(new Event("connectStatusUpdated"));
		}
		
		private function eventToTnStartCurrenctView(event:Event):void
		{
			if(_tnStartCurrectView != null)
			{
				_tnStartCurrectView.dispatchEvent(event);
			}
		}
		
		public function onClose(e:Event):void
		{
			eventToTnStartCurrenctView(new Event("connectStatusUpdated"));
		}
		
		protected function onSocketOnError(event:IOErrorEvent):void
		{
			eventToTnStartCurrenctView(new Event("connectStatusUpdated"));
		}
		
		protected function onSocketOnSecurityError(event:SecurityErrorEvent):void
		{
			eventToTnStartCurrenctView(new Event("connectStatusUpdated"));
		}
		
		public function onConnected(e:Event):void
		{
			eventToTnStartCurrenctView(new Event("connectStatusUpdated"));
		}
		
		public static function getInstance():LocalHomeControlSocketDataImpl{
			if(instance == null)
			{
				instance = new LocalHomeControlSocketDataImpl();
			}
			return instance;
			
		}
		
		public function checkConnection():void
		{
			if(!socket.connected){
				conn();
			}	
		}		
		
		public function disconnect():void
		{
			if(socket != null)
			{
				socket.close();
			}
		}
		
		public function reConnect():void
		{
			disconnect();
			checkConnection();
		}
		
		public function isConnected():Boolean
		{
			return socket.connected;
		}
		
		//desc: netid#deviceid#datactl#chNo
		private function findDesByItemId(itemIndex:int):String
		{
			var desc:String = "";
			if(_dataToPush != null)
			{
				var item:Item = _dataToPush.dbManager.itemDAO.get(itemIndex);
				desc = item.description;
			}
			return desc;
		}
		
		public function makeControlByteArray(itemIndex:int,controlCommandBean:ControlCommandBean):ByteArray
		{
			var desc:String = findDesByItemId(itemIndex);
			var lightArray:Array = desc.split("#");
			var byteArray:ByteArray = new ByteArray();
			var bodyByteArray:ByteArray = new ByteArray();		
			bodyByteArray.writeByte(FRAME_TYPE_CONTROL);		
			bodyByteArray.writeByte((Number)(lightArray[2]));
			bodyByteArray.writeByte((Number)(lightArray[3]));
			bodyByteArray.writeByte(controlCommandBean.data2);
	
			if(controlCommandBean.data3 != -1)
			{
				bodyByteArray.writeByte(controlCommandBean.data3 & 0xff);
			}
			bodyByteArray.writeByte(controlCommandBean.data4);
			bodyByteArray.writeByte(controlCommandBean.data5);
			bodyByteArray.writeByte(controlCommandBean.data6);
			byteArray.writeByte(SYN_HEAD);
			byteArray.writeByte(bodyByteArray.length + HEAD_LEN);
			byteArray.writeByte((Number)(lightArray[0]));
			byteArray.writeByte((Number)(lightArray[1]));
			byteArray.writeByte(0);
			byteArray.writeByte(0);
			byteArray.writeBytes(bodyByteArray);
			return byteArray;
		}
		
		public function sendControlData(byteArray:ByteArray):Boolean
		{
			if(isConnected())
			{
				socket.writeBytes(byteArray);
				socket.flush();
				return true;
			}
			return false;
		}
		
		public function sendQueryStatusData(commandByte:int):Boolean
		{
			if(isConnected())
			{
				socket.writeByte(SYN_HEAD);
			
				if(_tnStartCurrectView != null)
				{
					
				}
				
				socket.writeByte(commandByte & 0xff);
				socket.writeByte(TAIL);
				socket.flush();
				return true;
			}
			return false;
		}
		
		public function set tnStartCurrectView(value:View):void
		{
			if(_tnStartCurrectView != null)
			{
				_tnStartCurrectView = null;
			}
			_tnStartCurrectView = value;
		}

		public function get host():String
		{
			return _host;
		}

		public function set host(value:String):void
		{
			_host = value;
		}

		public function get port():int
		{
			return _port;
		}

		public function set port(value:int):void
		{
			_port = value;
		}

		public function get tnStartCurrectView():View
		{
			return _tnStartCurrectView;
		}

		public function get dataToPush():DataSingleton
		{
			return _dataToPush;
		}

		public function set dataToPush(value:DataSingleton):void
		{
			_dataToPush = value;
		}


	}
	
}